package com.terren.pc.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.terren.pc.common.config.SysConfig;


/**
 * 通用工具类
 * 
 */
public class CommonUtil {
	static Logger logger = LogManager.getLogger(CommonUtil.class);

	/**
	 * html字符串转义特殊字符
	 * 
	 * @param message
	 * 
	 */
	public static String filter(String message) {

		if (message == null) {
			return (null);
		}
		char content[] = new char[message.length()];
		message.getChars(0, message.length(), content, 0);
		StringBuilder result = new StringBuilder(content.length + 50);
		for (int i = 0; i < content.length; i++) {
			switch (content[i]) {
			case '<':
				result.append("&lt;");
				break;
			case '>':
				result.append("&gt;");
				break;
			case '&':
				result.append("&amp;");
				break;
			case '"':
				result.append("&quot;");
				break;
			default:
				result.append(content[i]);
			}
		}
		return (result.toString());

	}

	/**
	 * 拼接字符串
	 * 
	 * @param list
	 * @return
	 */
	public static String listToString(List<String> list) {
		StringBuilder builder = new StringBuilder();
		int i = 0;
		for (String oneText : list) {
			if (i > 0) {
				builder.append(",");
			}
			builder.append(oneText);
		}
		return builder.toString();
	}

	/**
	 * 转换IP地址
	 * 
	 * @param ip
	 * @return
	 */
	public static String getIpStringFromBytes(long ip) {
		StringBuilder sb = new StringBuilder();
		sb.append(ip >> 24);
		sb.append('.');
		sb.append(ip >> 16 & 0xFF);
		sb.append('.');
		sb.append(ip >> 8 & 0xFF);
		sb.append('.');
		sb.append(ip & 0xFF);
		return sb.toString();
	}

	/**
	 * 有些情况下ext treePanel node 会重复，为了防止重复，会添加 -xxx 样式的后缀，当使用该 node 时，需要去掉后缀 如
	 * 1-level1， 此 node 中 1 为真实node
	 * 
	 * @param nodeIdStr
	 * @return
	 */
	public static String clearNodeId(String nodeIdStr) {
		int index = nodeIdStr.indexOf("-");

		if (index > 0) {
			nodeIdStr = nodeIdStr.substring(0, index);
		}
		return nodeIdStr;
	}

	/**
	 * 字符串首字母大写
	 * 
	 * @param 字符串
	 * @return 首字母大写的字符串
	 */
	public static String toFirstUpperCase(String str) {
		if (str == null || str.length() < 1) {
			return "";
		}
		String start = str.substring(0, 1).toUpperCase();
		String end = str.substring(1, str.length());
		return start + end;
	}

	/**
	 * 获得随机数
	 * 
	 * @param minInt
	 * @param maxInt
	 * @return
	 */
	public static int getRandomInt(int minInt, int maxInt) {
		int number = maxInt - minInt + 1;

		Random random = new Random();

		int ranNum = random.nextInt(number) + minInt;// 0-5

		return ranNum;
	}

	/**
	 * 获得唯一ID
	 * 
	 * @return
	 */
	public static String getSingleId() {
		String formatType = "yyyyMMddHHmmsssss";
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat(formatType);

		String singleId = format.format(date);

		int ran = getRandomInt(0, 1000);

		singleId = singleId + "-" + ran;

		return singleId;
	}

	/**
	 * 获得登录用户 ip
	 * 
	 * @return
	 */
	public static String getLoginIp(HttpServletRequest request) {

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}

	public static <T> String getProjectPath(Class<T> cls) {
		String filePath = null;
		try {
			URL url = cls.getProtectionDomain().getCodeSource().getLocation();
			filePath = URLDecoder.decode(url.getPath(), "utf-8");
			if (filePath.endsWith(".jar")) {
				filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
			}
			File file = new File(filePath);
			filePath = file.getAbsolutePath();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return filePath;
	}

	/**
	 * 配置文件
	 * 
	 * @param filePath
	 * @param keyWord
	 * @return
	 */
	public static String getProperties(String filePath, String keyWord) {
		Properties prop = null;
		String value = null;
		try {
			// 通过Spring中的PropertiesLoaderUtils工具类进行获取
			prop = PropertiesLoaderUtils.loadAllProperties(filePath);
			// 根据关键字查询相应的值
			value = prop.getProperty(keyWord);
		} catch (IOException e) {
			logger.error("读取配置文件错误:"+filePath,e);
		}
		return value;
	}

	/**
	 * 
	 * @return
	 */
	public static Properties getSysConfigProperties() {
		InputStream resourceAsStream = null;
		String appRoot = System.getProperty("app.root");
		File appPath = Paths.get(appRoot, "config","system","sysconfig.properties").toFile();
		String configPath;
		if (appPath.exists()) {
			configPath = appPath.getPath();
			logger.debug("[app.root:"+configPath+"]");
			try {
				resourceAsStream = new FileInputStream(configPath);
			} catch (FileNotFoundException e) {
				logger.error("没有找到配置文件:"+configPath);
			}
		}else{
			configPath =SysConfig.CONFIG_FILE_NAME;
			resourceAsStream = CommonUtil.class.getClassLoader().getResourceAsStream(configPath);
			if (resourceAsStream == null) {
	            logger.error("没有找到配置文件:"+configPath);
	            return null;
	        }
		}
		Properties properties = new Properties();
		try {
			 properties.load(resourceAsStream);
		} catch (IOException e) {
			logger.error("读取配置文件错误:"+SysConfig.CONFIG_FILE_NAME,e);
		}  
		if (null!= properties) {
			logger.info("读取配置文件:"+configPath);
		}
        return properties;
	}
	
	/**
	 * 两个整数想除获得小数
	 * @param a 被除数
	 * @param b 除数
	 * @param c 保留小数位数
	 * @return
	 */
	public static Double getDouble(Long a, Long b, int c) {
		return new BigDecimal((double)a/b).setScale(c, BigDecimal.ROUND_HALF_UP).doubleValue();
	}
}
